import mqtt, { MqttClient } from 'mqtt'
import EventEmitter from 'events';

export default class Mqtt {
    private client:MqttClient | undefined;
    private eventEmitter:EventEmitter;
    private options = {
        host : '',
        port : 0,
        username : '',
        password : ''
    }
    constructor(params : {host:string; port:number; username:string; password:string;}) {
        this.options.host =  params.host
        this.options.port =  params.port
        this.options.username =  params.username
        this.options.password =  params.password

        this.eventEmitter = new EventEmitter()
    }

    on<T>(event:'connect'|'message', listener:(data:T) => void) {
        this.eventEmitter.on(event, listener)
        return this
    }

    connect() {
        this.client = mqtt.connect(this.options)
        this.client.on('connect', () => {
            this.eventEmitter.emit('connect')
        })

        this.client.on('message', (topic, message) => {
            this.eventEmitter.emit('message', {topic, message})
        })
    }

    subscribe(topic:string|string[]) {
        this.client?.subscribe(topic, {qos : 2})
    }

    publish(topic:string, data:string|Buffer) {
        this.client?.publish(topic, data, {qos : 2}, (a, b) => {
		})
    }
}